package online.hxstart.code.leetcode;

/** @author huxing */
public class FindMedianSortedArrays {

  public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    int len = nums1.length + nums2.length;
    int i = 0, i2 = 0, da1, da2;
    if (nums1.length < nums2.length) {
      int[] te = nums1;
      nums1 = nums2;
      nums2 = te;
    }
    int daIndex = 0;
    int[] data = new int[len / 2 + 1];
    for (int i1 = 0; i <= len / 2 + 1; i1++, i++) {
      if (i1 < nums1.length) {
        da1 = nums1[i1];
        if (i2 < nums2.length) {
          for (; i2 < nums2.length + 1 && i < len / 2 + 1; i2++, i++) {
            if (i2 < nums2.length) {
              da2 = nums2[i2];
              if (da1 < da2) {
                data[daIndex] = da1;
                daIndex++;
                break;
              } else {
                data[daIndex] = da2;
                daIndex++;
              }
            } else {
              data[daIndex] = da1;
              daIndex++;
            }
          }
        } else {
          data[daIndex] = da1;
          daIndex++;
          if (daIndex >= len / 2 + 1) {
            break;
          }
        }
      } else if (i <= len / 2) {
        data[daIndex] = nums2[i2];
        daIndex++;
      }
    }
    int a = len / 2;
    if (len % 2 == 0) {
      return (data[a - 1] + data[a]) / 2.0;
    } else {
      return data[a];
    }
  }

  public static void main(String[] args) {
    FindMedianSortedArrays a = new FindMedianSortedArrays();
    System.out.println(a.findMedianSortedArrays(new int[] {}, new int[] {1, 2, 3, 4}));
    //
  }
}
